﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Collections;

namespace PowerCard
{
    public partial class Form1 : Form
    {
        int Flag = 0;
        DataTable tb = new DataTable();
        int SendCount = 0;
        IPAddress ServerIp = IPAddress.Parse(System.Configuration.ConfigurationSettings.AppSettings["MessHost1"].ToString());

        private Semaphore m_maxNumberAcceptedClients; //限制访问接收连接的线程数，用来控制最大并发数

        //IPEndPoint iep = new IPEndPoint(ServerIp, 6006);
        //Socket _newSocket;
        //IPEndPoint iep = new IPEndPoint(serverIp, serverPort);
        //Socket _socket = new SocketSend(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        Socket socket;
        Thread mythread;
        private static Hashtable hashpoint = new Hashtable();
        Thread insertDataBase;
        private static int COUNT = 0;

        int insertdatabaseTime = int.Parse(System.Configuration.ConfigurationSettings.AppSettings["insertDateBase"].ToString());
        DataTable dt1send = new DataTable();
        public Form1()
        {
            InitializeComponent();
            
            mythread = new Thread(new ThreadStart(BeginListen));
            mythread.IsBackground = true;
            mythread.Start();

            insertDataBase = new Thread(new ThreadStart(InsertListen));
            insertDataBase.IsBackground = true;
            insertDataBase.Start();
        }
        public string changetwoX(string hex)
        {
            if (hex.Length < 2)
                return "0" + hex;
            else
                return hex;
        }

        private void BeginListen()
        {
            //IPAddress ServerIp = IPAddress.Parse("192.168.1.13");

            IPEndPoint iep = new IPEndPoint(ServerIp, int.Parse(System.Configuration.ConfigurationSettings.AppSettings["MessPort1"].ToString()));

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Bind(iep);

            int maxCount = int.Parse(System.Configuration.ConfigurationSettings.AppSettings["time"].ToString());
            this.socket.Listen(maxCount);

            while (true)
            {
                try
                {
                    Socket _newSocket = this.socket.Accept();

                    ThreadPool.QueueUserWorkItem(new WaitCallback(this.Start_Thread), _newSocket);                 
                }
                catch (Exception ex)
                {
                    PowerCard.Power.Write2("-------------------异常003_--------------");
                    PowerCard.Power.Write2(ex.StackTrace);
                    PowerCard.Power.Write2(ex.Message.ToString());
                }
                // PowerCard.Power.Write2("-------------------COUNT_--------------" + COUNT);
            }
        }

        private void Start_Thread(Object _newSocket)
        {
            //Power.Write2("Socket建立等待心跳包！");
            Socket newSocket = (Socket)_newSocket;

            newSocket.NoDelay = true;
            newSocket.LingerState = new LingerOption(true, 10);
            newSocket.ReceiveTimeout = int.Parse(System.Configuration.ConfigurationSettings.AppSettings["timeOut"].ToString());

            while (true)
            {
                try
                {

                    byte[] byteMessage;
                    byteMessage = new byte[1024];

                    if (!newSocket.Connected)
                    {
                        //PowerCard.Power.Write2("-------------------UnConnected--------------");
                        newSocket.Close();
                        return;
                    }

                    Interlocked.Increment(ref COUNT);
                    //PowerCard.Power.Write2("-------------------Receive--------------");
                    newSocket.Receive(byteMessage);

                    string nn = System.Text.Encoding.Default.GetString(byteMessage);

                    if (nn.Split(',')[0].Trim() == "15123207113")
                    {
                        PowerCard.Power.Write("-------------心跳" + nn.Split(',')[0].Trim() + "---------------");
                    }

                    if (!hashpoint.ContainsKey(nn.Split(',')[0].Trim()))
                    {
                        hashpoint.Add(nn.Split(',')[0].Trim(), DateTime.Now.ToString());
                    }
                    string sql12 = "SELECT TOP 50 * FROM Meter_Operation WHERE MO_State in (0,-10,-20) AND MO_MC_No='" + nn.Split(',')[0].Trim() + "' AND (MO_Expect_Date IS NULL OR MO_Expect_Date <='" + DateTime.Now.ToString() + "') ORDER BY MO_Id ASC";

                    DataTable tb11 = DBClass.GetDataTable1(sql12);

                    int a = 0;

                    foreach (DataRow rw in tb11.Rows)
                    {
                        if (rw["MO_MB_No"].ToString().Length < 8)
                        {
                            string sql1 = "UPDATE Meter_Operation SET MO_State=-30,MO_Recive_Date='" + DateTime.Now.ToString() + "'WHERE MO_Id=" + rw["MO_Id"].ToString();
                            DBClass.ExeNonQuery(sql1);
                            continue;
                        }

                        SocketSend ss = new SocketSend();
                        a = ss.Send_SMS_Point(newSocket, rw);

                        if (a == -1)
                        {
                            break;
                        }

                        string sqlsenddate = "UPDATE Meter_Operation SEt MO_Send_Date='" + DateTime.Now.ToString() + "' WHERE MO_Id=" + rw["MO_Id"].ToString();
                        DBClass.ExeNonQuery(sqlsenddate);
                        DBClass.ExeNonQuery1(sqlsenddate);
                        Thread.Sleep(1500);
                    }

                }
                catch (Exception ex)
                {
                    PowerCard.Power.Write2("-------------------异常001_--------------");
                    PowerCard.Power.Write2(ex.StackTrace);
                    PowerCard.Power.Write2(ex.Message.ToString());
                }
                finally
                {
                    try
                    {
                        Interlocked.Decrement(ref COUNT);
                        if (newSocket.Connected)
                        {
                            newSocket.Shutdown(SocketShutdown.Both);
                        }
                        newSocket.Close();
                    }
                    catch (Exception e)
                    {
                        PowerCard.Power.Write2("-------------------异常001_1--------------");
                        PowerCard.Power.Write2(e.StackTrace);
                        PowerCard.Power.Write2(e.Message.ToString());
                    }
                }
            }
        }


        private void InsertListen()
        {
            while (true)
            {
                try
                {
                    PowerCard.Power.Write2("-------------------hashpoint长度_--------------" + hashpoint.Count.ToString());
                    string sqltime = "";
                    foreach (DictionaryEntry de in hashpoint)
                    {
                        de.Key.ToString();
                        de.Value.ToString();
                        sqltime += "Update Meter_Collector SET MC_Create_Date='" + de.Value.ToString() + "' WHERE MC_No='" + de.Key.ToString() + "';";
                    }

                    if (!string.IsNullOrEmpty(sqltime))
                    {
                        PowerCard.Power.Write2("-------------------更新采集器时间--------------");
                        DBClass.ExeNonQuery(sqltime);
                    }
                    hashpoint.Clear();
                    //dt1send = DBClass.GetDataTable("SELECT MC_No FROM Meter_Collector");
                    Thread.Sleep(insertdatabaseTime);
                }
                catch (Exception ex)
                {
                    PowerCard.Power.Write2("-------------------异常002_--------------");
                    PowerCard.Power.Write2(ex.StackTrace);
                    PowerCard.Power.Write2(ex.Message.ToString());
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            
        }
    }
}